#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;

class Point
//这是一个固定用法
: public std::enable_shared_from_this<Point>
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;   }

    ~Point() {  cout << "~Point()" << endl; }

    //需求: 希望在成员函数内部获取本对象的智能指针shared_ptr
    //答：只要让Point类型继承自一个辅助类std::enable_shared_from_this
    //该类内部拥有一个成员函数 shared_from_this，可以解决我们的需求
    shared_ptr<Point> addPoint(Point & pt)
    {
        this->_ix += pt._ix;
        this->_iy += pt._iy;
        return shared_from_this();
    }

    void print() const
    {   cout << "(" << _ix << "," << _iy << ")" << endl;}

private:
    int _ix;
    int _iy;
};

void test3()
{
    //一般情况下，将一个堆对象交给一个智能指针进行托管之后，
    //接下来所有的操作都要交给智能指针完成，这样可以尽量出现误用情况
    shared_ptr<Point> sp(new Point(1, 2));
    shared_ptr<Point> sp2(new Point(11, 12));

    //sp与sp托管的对象都是同一个对象,造成误用
    shared_ptr<Point> sp3(sp->addPoint(*sp2));

    cout << "sp.use_count(): " << sp.use_count() << endl;
    cout << "sp2.use_count(): " << sp2.use_count() << endl;
    cout << "sp3.use_count(): " << sp3.use_count() << endl;
}


int main()
{
    /* test0(); */
    /* test1(); */
    /* test2(); */
    test3();
    return 0;
}

